<?php

namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use Helper;

class Accounts extends ActiveRecord
{


    public static $allowTypes = ['email', 'voice', 'sms'];

    public static function tableName()
    {
        return '{{%accounts}}';
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['addtime'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['uptime']
                ]
            ],

        ];
    }

    public function rules()
    {
        return [
            ['appkey', 'required', 'message' => Yii::t('code', '1041')],
            ['optype', 'checkOpType'],
            ['total', 'checkTotal'],
            [['total', 'balance'], 'integer']
        ];
    }

    public function checkOpType($attribute, $params)
    {
        if ($this->optype) {
            if (!in_array($this->optype, self::$allowTypes)) {
                $this->addError($attribute, Yii::t('code', '1043'));
            }
        } else {
            $this->addError($attribute, Yii::t('code', '1043'));
        }
    }

    public function checkTotal($attribute, $params)
    {
        if ($this->total <= 0 || !is_numeric($this->total)) {
            $this->addError($attribute, Yii::t('code', '1046'));
        }
    }

    /**
     * 更新余额缓存
     * @param $appkey 用户appkey
     * @return bool 返回操作结果
     */
    public static function updateBalanceCache($appkey, $optype = 'all')
    {
        if ($optype == 'all') {
            $accounts = Accounts::find()->where(['appkey' => $appkey])->asArray()->all();
        } else {
            $accounts = Accounts::find()->where(['appkey' => $appkey, 'optype' => $optype])->asArray()->all();
        }
        if (!empty($accounts)) {
            foreach ($accounts as $k => $v) {
                $name = 'balanceCache_' . $appkey . '_' . $v['optype'];
                Yii::$app->redis->set($name, $v['balance']);
            }
        }
        return true;
    }

    /**
     * 获取余额信息
     * @param $appkey 用户appkey
     * @param string $optype 用户操作类型
     * @return int|mixed 返回余额值
     */
    public static function getBalanceCache($appkey, $optype = 'sms')
    {
        $balance = 0;
        $name = 'balanceCache_' . $appkey . '_' . $optype;
        $balance = Yii::$app->redis->get($name);
        if (empty($balance) && $balance != '0') {
            $account = Accounts::find()->where(['appkey' => $appkey, 'optype' => $optype])->asArray()->one();
            $balance = $account ? $account['balance'] : 0;
        }
        return $balance;
    }

    /**
     * 变更余额条数
     * @param $appkey 用户appkey
     * @param $num 变更数量
     * @param $optype 操作类型
     * @return bool 返回操作结果
     */
    public static function auotBalanceCache($appkey, $num, $optype)
    {
        $name = 'balanceCache_' . $appkey . '_' . $optype;
        $balance = Yii::$app->redis->get($name);
        if (empty($balance) && $balance != '0') {
            self::updateBalanceCache($appkey);
        } else {
            $balance += $num;
            Yii::$app->redis->set($name, $balance);
        }
        return true;
    }


}


?>